//
//  HMOAuthViewController.swift
//  sinaweibo
//
//  Created by lst on 16/5/22.
//  Copyright © 2016年 lst. All rights reserved.
//

import UIKit
import SVProgressHUD

//偏好设置保存的KEY
private let userInfoKey = "com.ithema.userInfoKey"

class HMOAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    override func loadView() {
        //设置界面为UIWebView
        view = webView
        webView.opaque = false
        webView.backgroundColor = UIColor.whiteColor()
        webView.delegate = self
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavBar()
        loadOauthPath()
    }
    override func viewWillDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
    }
    //打开授权页面
    func loadOauthPath(){
       //获取req 对象
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)!
        let req = NSURLRequest(URL: url)
        webView.loadRequest(req)
    }
    
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    


}
extension HMOAuthViewController{
    //关闭按钮的点击事件
    @objc private func closed(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //
    @objc private func testAccount() {
        //使用webView 执行js 字符串
        //js 动态注入
        let jsString = "document.getElementById('userId').value = 'leiggee@126.com', document.getElementById('passwd').value = 'onoyomg' "
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }

    //设置导航控制器
    private func setNavBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector( HMOAuthViewController.closed))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账户", target: self, action: #selector(HMOAuthViewController.testAccount))
    }
    

    
}


extension HMOAuthViewController: UIWebViewDelegate{
    func webViewDidStartLoad(webView: UIWebView) {
        //显示用户等待指示器
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        //隐藏用户等待指示灯
        SVProgressHUD.dismiss()
    }
    //授权成功后 就会回调新页面 再回调页面的地址中包含code(授权码)
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //打印url
        let urlString = request.URL?.absoluteString ?? ""
        
        //截取收取成功的字符串中的code
        //定义授权成功的标记
        let successFlag = "code="
        if urlString.containsString(successFlag) {
            //授权成功
            //"!"标示程序员 确保一定能够找到对应字符串所在位置
            let range = urlString.rangeOfString(successFlag)!
//            let subStr = urlString.substringFromIndex(range.endIndex)
            let code = urlString.substringFromIndex(range.endIndex)
            
//            print(code,urlString)
            //获取code 之后 应该使用code码  请求token(用户访问令牌)
//            loadAccessToken(code)
            HMUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code, finished: { (isSuccess) in
                //闭包的参数需要重谢
                if !isSuccess{
                    SVProgressHUD.showErrorWithStatus(AppErrorTip)
                    return
                }
                //请求成功

                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewController, object: nil)
            })
            //不加载网页
            return false
        }
        return true
    }
    //使用code 加载用户授权的token()令牌
    private func loadAccessToken(code:String){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id" : client_id, "client_secret":client_secret, "grant_type": "authorization_code","code":code,"redirect_uri":redirect_uri]
        
        HMNetworkTools.sharedTools.request(.POST, urlString: urlString, parameters: parameters) { (responseObject, error) in
//            print(responseObject,error)
            // 请求token 成功之后  使用token 和 uid 获取用户信息
            if error != nil{
                SVProgressHUD.showWithStatus(AppErrorTip)
                return
            }
            //请求成功
            self.loadUserInfo(responseObject)
        }

    }
    //请求用户信息
    private func loadUserInfo(response: AnyObject?){
        guard let result = response as? [String : AnyObject]else{
            SVProgressHUD.showWithStatus(AppErrorTip)
            return
        }
        
        let token = result["access_token"]!
        let uid = result["uid"]!
        let urlStirng = "https://api.weibo.com/2/users/show.json"
        //字典中不可以添加 nil
        let parameters = ["access_token": token, "uid": uid]
        
        HMNetworkTools.sharedTools.request(.GET, urlString: urlStirng, parameters: parameters) { (responseObject, error) in
            if error != nil {
                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                return
            }
            //请求成功
//            print(responseObject)
            //用户信息  就应该保存用户信息到本地
            guard var dict = responseObject as? [String : AnyObject] else{
                SVProgressHUD.showWithStatus(AppErrorTip)
                return
            }
            //用户信息保存到偏好设置(合并两个字典)
            for (key, value) in result {
                dict[key] = value
            }
         
            //使用偏好设置 保存字典数据

            //将dict 转模型
            let user = HMUserAccount(dict:dict)
            //将模型转字典
            let keys = ["access_token","expires_in","uid","name","avatar_large"]
            let userInfo = user.dictionaryWithValuesForKeys(keys)
//            print(userInfo)
//            保存字典数据
            let userDefaults = NSUserDefaults.standardUserDefaults()
            //不能向偏好设置中保存  nil
            userDefaults.setObject(userInfo, forKey: userInfoKey)
            //同步更新
            userDefaults.synchronize()
//            print(NSHomeDirectory())
            
        }
    }
    
}
